package org.pidan.basic.multiThread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * {@code @description}: ReentrantLock 实例
 * {@code @author}: huangyuxin
 * {@code @date}: 2023-12-13
 */
public class ReentrantLockDemo1 {

    private static int num = 0;

    //创建锁
    private static ReentrantLock lock = new ReentrantLock();

    private static void add() {

        //加锁
        lock.lock();

        // 可重入锁演示：可以获取锁两次，如果是不可重入锁，这里会因为拿不到上一个锁而死锁
//        lock.lock();

        try {
            num++;
        } finally {
            //解锁
            lock.unlock();
            //获取几次锁就需要解几次锁
//            lock.unlock();
        }
    }

    public static class T1 extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < 1000; i++) {
                ReentrantLockDemo1.add();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        T1 t1 = new T1();
        T1 t2 = new T1();
        T1 t3 = new T1();

        t1.start();
        t2.start();
        t3.start();


        t1.join();
        t2.join();
        t3.join();

        System.out.println(ReentrantLockDemo1.num);
    }
}
